from flaskapp.services.stat import find_day_data, find_month_data, find_model_data, find_device_data,find_system_data
from flask import Blueprint, jsonify, request
from flask_jwt_extended import (get_jwt_identity, jwt_required)
import json
import logging
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)


stat_bp = Blueprint('stat', __name__)


@stat_bp.route('/api/stat/day', methods=['GET'])
# @jwt_required()
def get_day_data():
    try:
        timeStr = request.values.get('time', datetime.now())
        time = datetime.strptime(timeStr, "%Y-%m-%d")
        print(time)
        count = find_day_data(time)
        return jsonify({"code": 0, "data": count})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})


@stat_bp.route('/api/stat/twoday', methods=['GET'])
# @jwt_required()
def get_twoday_data():
    try:
        count1 = find_day_data(datetime.now()+timedelta(days=-1))
        count2 = find_day_data(datetime.now())
        data = {}
        data["0"] = count1
        data["1"] = count2
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting data: {e.args}")
        return jsonify({"error": "Failed to get data"})


@stat_bp.route('/api/stat/month', methods=['GET'])
# @jwt_required()
def get_month_data():
    try:
        time = datetime.now()
        data = find_month_data(time)
        # data={}
        # data[time.strftime("%Y")]=ret
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})


@stat_bp.route('/api/stat/device', methods=['GET'])
# @jwt_required()
def get_device_data():
    try:
        data = find_device_data()
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})


@stat_bp.route('/api/stat/model', methods=['GET'])
# @jwt_required()
def get_model_data():
    try:
        # typeList=request.values.getlist('type')
        # print(typeList)
        list = ['fire', 'person', 'hat', 'face']
        ret = find_model_data(list)
        return jsonify({"code": 0, "data": ret})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})

@stat_bp.route('/api/stat/system', methods=['GET'])
# @jwt_required()
def get_system_data():
    try:
        data = find_system_data()
        return jsonify({"code": 0, "data": data})
    except Exception as e:
        logger.error(f"Error getting data: {e}")
        return jsonify({"error": "Failed to get data"})
